import { NextResponse, NextRequest } from 'next/server'
import db, { todoQueries, todoProjectLinkQueries, userQueries, createAuditLog } from '@/lib/database-prisma' // 导入 db 实例和 createAuditLog
import { getUserFromRequest } from "@/lib/auth-utils"

interface TodoRequestBody {
  content: string
  tags?: string[]
  status: string
  // created_by is now derived from session/request
  project_id: number
  assigned_to?: number | null
}

interface User {
    id: number;
    name: string;
    color: string;
    casdoor_id?: string;
    email?: string;
    avatar?: string;
    created_at: string;
}

interface Todo {
    id: number;
    content: string;
    created_by: number;
    tags: string | null;
    status: '待完成' | '进行中' | '待测试' | '已完成';
    assigned_to: number | null;
    archived: boolean;
    created_at: string;
    // Joined fields
    creator_name?: string;
    creator_color?: string;
    assignee_name?: string | null;
    assignee_color?: string | null;
}

export async function POST(request: NextRequest) {
  const currentUser = await getUserFromRequest(request);
  if (!currentUser || !currentUser.id) {
    return NextResponse.json({ message: '用户未认证或无法获取用户ID' }, { status: 401 });
  }
  const currentUserId = currentUser.id;

  try {
    const body: TodoRequestBody = await request.json();

    // Basic field validation
    if (!body.content || !body.status || !body.project_id) {
      return NextResponse.json({ message: '缺少必要字段: content, status, project_id' }, { status: 400 })
    }

    const tagsString = body.tags && body.tags.length > 0 ? body.tags.join(',') : null

    // 创建TODO（不使用事务，像项目创建一样）
    const createResult = await todoQueries.create.run(
      body.content,
      currentUserId,
      tagsString,
      body.status,
      body.assigned_to || null
    );
    const newTodoId = createResult.lastInsertRowid as number;
    if (!newTodoId) {
      throw new Error('创建todo失败');
    }

    // 添加项目关联
    await todoProjectLinkQueries.create.run(newTodoId, body.project_id);

    // 获取完整数据（在事务外部）
    const createdTodoRaw = await todoQueries.findById.get(newTodoId);
    if (!createdTodoRaw) {
      return NextResponse.json({ message: '创建todo后无法查询到该todo' }, { status: 500 });
    }

    const creator = await userQueries.findById.get(createdTodoRaw.createdBy);
    const assignee = createdTodoRaw.assignedTo ? await userQueries.findById.get(createdTodoRaw.assignedTo) : null;

    const populatedTodo = {
      ...createdTodoRaw,
      creator_name: creator?.name,
      creator_color: creator?.color,
      assignee_name: assignee?.name,
      assignee_color: assignee?.color,
    };

    // 创建审计日志（异步执行，不阻塞响应）
    createAuditLog(
      currentUserId,
      {
        type: "todo",
        id: populatedTodo.id,
        user: currentUser.name,
        act: "create",
        fieldsChanged: ["content", "status", "tags", "assigned_to"],
        newValue: {
          content: populatedTodo.content,
          status: populatedTodo.status,
          tags: populatedTodo.tags,
          assigned_to: populatedTodo.assignedTo
        },
        time: new Date().toISOString()
      },
      body.project_id,
      populatedTodo.id
    ).catch(auditError => {
      console.error('创建TODO审计日志失败:', auditError);
    });

    return NextResponse.json(populatedTodo, { status: 201 });

  } catch (error: any) {
    console.error('创建TODO任务失败:', error);
    if (error.message && error.message.includes('FOREIGN KEY constraint failed')) {
      return NextResponse.json({ message: '外键约束失败，请检查 project_id 或 assigned_to 是否有效' }, { status: 400 });
    }
    return NextResponse.json({ message: `服务器内部错误: ${error.message || '未知错误'}` }, { status: 500 });
  }
}

export async function GET(request: NextRequest) {
  const currentUser = await getUserFromRequest(request);
  if (!currentUser || !currentUser.id) {
    return NextResponse.json({ message: '用户未认证或无法获取用户ID' }, { status: 401 });
  }

  try {
    const { searchParams } = new URL(request.url);
    const project_id = searchParams.get('project_id');
    const assigned_to = searchParams.get('assigned_to');
    const status = searchParams.get('status');

    if (project_id) {
      // Get todos for a specific project
      const projectIdNum = parseInt(project_id, 10);
      if (isNaN(projectIdNum)) {
        return NextResponse.json({ message: '无效的项目ID' }, { status: 400 });
      }

      const todos = await todoQueries.getAllByProjectId.all(projectIdNum);
      
      // Populate creator and assignee information
      const populatedTodos = await Promise.all(
        todos.map(async (todo: any) => {
          const creator = await userQueries.findById.get(todo.createdBy);
          const assignee = todo.assignedTo ? await userQueries.findById.get(todo.assignedTo) : null;
          
          return {
            ...todo,
            creator_name: creator?.name,
            creator_color: creator?.color,
            assignee_name: assignee?.name,
            assignee_color: assignee?.color,
          };
        })
      );

      return NextResponse.json(populatedTodos);
    } else {
      // Get all todos (you might want to add pagination here)
      const todos = await todoQueries.getAllActive.all();
      
      // Populate creator and assignee information
      const populatedTodos = await Promise.all(
        todos.map(async (todo: any) => {
          const creator = await userQueries.findById.get(todo.createdBy);
          const assignee = todo.assignedTo ? await userQueries.findById.get(todo.assignedTo) : null;
          
          return {
            ...todo,
            creator_name: creator?.name,
            creator_color: creator?.color,
            assignee_name: assignee?.name,
            assignee_color: assignee?.color,
          };
        })
      );

      return NextResponse.json(populatedTodos);
    }

  } catch (error: any) {
    console.error('获取TODO任务失败:', error);
    return NextResponse.json({ message: `服务器内部错误: ${error.message || '未知错误'}` }, { status: 500 });
  }
} 